//
//  OAuthViewController.swift
//  WeiBoSwift
//
//  Created by zc on 16/6/24.
//  Copyright © 2016年 zc. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {
    let client_id = "4113689027"
    let redirect_url = "http://www.itcast.cn"
    let client_secret = "b912bc11639df56bd109b3be60c60246"
    //定义一个webView属性
    let webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
       // print(view)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
       // print(view)
        setupUI()
        //加载网页
        loadOAuthPage()
        // Do any additional setup after loading the view.
    }
    
    private func loadOAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_url)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        
    }
    
    private func setupUI() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(close))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(fullAccount))
    }
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fullAccount(){
        let jsString = "document.getElementById('userId').value = '15121148918' ,document.getElementById('passwd').value = 'z!c313363296';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
  
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

/*
 Optional(https://api.weibo.com/oauth2/authorize?client_id=1486450336&redirect_uri=http://www.itcast.cn)
 Optional(http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=2or41G&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D1486450336%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.itcast.cn%26from%3D%26with_cookie%3D)
 Optional(http://m.weibo.cn/reg/index?jp=1&wm=4406&appsrc=2or41G&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D1486450336%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.itcast.cn%26from%3D%26with_cookie%3D)
 come in
 Optional(https://api.weibo.com/oauth2/authorize?client_id=1486450336&redirect_uri=http://www.itcast.cn)
 Optional(https://api.weibo.com/oauth2/authorize)
 Optional(https://api.weibo.com/oauth2/authorize#)
 Optional(https://api.weibo.com/oauth2/authorize)
 Optional(http://www.itcast.cn/?code=739780e24a8ff3ba8f7ee7e2d976afdf)  不希望能够加载出来
 Optional(about:blank)
 Optional(about:blank)
 Optional(about:blank)
 
 */

//专门处理webView所有的协议方法
extension OAuthViewController:UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //协议方法 如果返回bool 一般为true 表示当前对象可以正常工作 否则不能
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       // print(request.URL)
        guard let urlString = request.URL?.absoluteString else{
            return false
        }
        //是网页请求页面 或者请求授权
       if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        if !urlString.hasPrefix(redirect_url) {
            return false
        }
        //程序走到这里 一定包含回调的URL
        guard let query = request.URL?.query else{
            return false
        }
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
     //   print(code)
        loadAccessToken(code)
        
    //
        
        //print(query)
        
        
        return false
    }
    
    private func loadAccessToken(code: String){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parmaters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_url]
        let afn = AFHTTPSessionManager()
        //AFN 默认只支持 @"application/json",@"text/json",@"text/javascript"
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
      //  afn.responseSerializer = AFJSONResponseSerializer()
        afn.POST(urlString, parameters: parmaters, progress: { (progress) in
            print(progress)
            }, success: { (_, result) in
                //将二进制数据装换成string
               // let str = NSString (data: result as! NSData, encoding: NSUTF8StringEncoding)
               // print(str)
                if let dict = result as? [String: AnyObject] {
                    //开始字典转模型
                    let account = UserAccount(dict: dict)
                   // print(account)
                    //相信后端的数据一定能取到对应的值
                    self.lodaUserInfo(account)
                }
                SVProgressHUD .dismiss()
            }) { (_, error) in
                print(error)
                SVProgressHUD.dismiss()
        }
        
    }
    
    private func lodaUserInfo(account :UserAccount){
        let  urlString = "https://api.weibo.com/2/users/show.json"
        let parmaters = ["access_token": account.access_token!, "uid": account.uid!]
        let afn = AFHTTPSessionManager()
        afn.GET(urlString, parameters: parmaters, progress: { (progress) in
           
            }, success: { (_, result) in
                if let dict = result as? [String :AnyObject] {
                    account.avatar_large = dict["avatar_large"] as? String
                    account.name = dict["name"] as? String
                      account.saveAccount()
                    
                }
            }) { (_, error) in
                print(error)
        }
    }
    
}

